package com.carreirati.evaluation.domain;

import org.springframework.roo.addon.dbre.RooDbManaged;
import org.springframework.roo.addon.javabean.RooJavaBean;
import org.springframework.roo.addon.jpa.activerecord.RooJpaActiveRecord;
import org.springframework.roo.addon.json.RooJson;
import org.springframework.roo.addon.tostring.RooToString;
import org.springframework.transaction.annotation.Transactional;

@RooJavaBean
@RooJpaActiveRecord(versionField = "", table = "user_profile", schema = "dbo")
@RooDbManaged(automaticallyDelete = true)
@RooJson
public class UserProfile {
	 @Transactional
	    public void persist() {
	        if (this.entityManager == null) this.entityManager = entityManager();
	        String promoDate = "";
	        if (this.getPromoDate() == "") promoDate = "null"; else promoDate = "'" + this.getPromoDate() + "'";
	        String sqlString = "INSERT INTO user_profile (profile_id, user_id,promo_date, is_last) ";
	        sqlString += " VALUES('" + this.getProfileId().getId() + "','" + this.getUserId().getId() + "'," + promoDate + ",'" + this.getIsLast() + "')";
	        this.entityManager.createNativeQuery(sqlString).executeUpdate();
	    }
	 
	   
	 @Transactional
	    public void remove() {
		 if (this.entityManager == null) this.entityManager = entityManager();
		 
			 String sqlString = "DELETE FROM user_profile WHERE id = ' " + this.getId() + "'";
	            this.entityManager.createNativeQuery(sqlString).executeUpdate();
	    }
	 
	 @Transactional
	    public UserProfile merge() {
	        if (this.entityManager == null) this.entityManager = entityManager();
	        String promoDate = "";
	        if (this.getPromoDate() == "") promoDate = "null"; else promoDate = "'" + this.getPromoDate() + "'";
	        this.setPromoDate(promoDate);
	        
	        String sqlString = "UPDATE user_profile SET profile_id = '" + this.getProfileId().getId() + "', user_id = '" + this.getUserId().getId() + "',promo_date = " + promoDate + ", is_last= '" + this.getIsLast() + "'  ";
	        sqlString += " WHERE id = '"+ this.getId() +"'";
	        this.entityManager.createNativeQuery(sqlString).executeUpdate();
	        UserProfile merged =  UserProfile.findUserProfile(this.getId());
	        this.entityManager.flush();
	        return merged;
	    }
	 
	 
	  public Long findLastUserProfileId() {
		 if (this.entityManager == null) this.entityManager = entityManager();
	    	String sqlString = "SELECT max(id) FROM user_profile WHERE profile_id ='" + this.getProfileId().getId() + "' AND user_id = '" + this.getUserId().getId() + "'";	        
	    	 java.math.BigInteger aux = (java.math.BigInteger)this.entityManager.createNativeQuery(sqlString).getSingleResult();
	        return aux.longValue();

	    }
	 
	 
	 
   
}
